#!/bin/bash

# TZAI 管理后台前端部署脚本
# 部署到阿里云服务器 39.97.249.188

set -e

SERVER="39.97.249.188"
SERVER_USER="root"
REMOTE_PATH="/usr/share/nginx/html/tzai"
LOCAL_BUILD_PATH="tzai-backend/ruoyi-ui/dist"

echo "======================================"
echo "TZAI 管理后台前端部署脚本"
echo "======================================"
echo ""
echo "服务器: $SERVER"
echo "远程路径: $REMOTE_PATH"
echo ""

# 检查是否已构建
if [ ! -d "$LOCAL_BUILD_PATH" ]; then
    echo "❌ 错误: 未找到构建产物"
    echo "请先运行: cd tzai-backend/ruoyi-ui && ./build-prod.sh"
    exit 1
fi

echo "1. 检查构建产物..."
echo "✅ 构建产物存在"
echo ""

# 显示构建产物大小
echo "📊 构建产物大小:"
du -sh $LOCAL_BUILD_PATH
echo ""

# 创建远程目录
echo "2. 创建远程目录..."
ssh $SERVER_USER@$SERVER "mkdir -p $REMOTE_PATH"

# 备份现有文件（可选）
echo "3. 备份现有文件..."
BACKUP_NAME="tzai_backup_$(date +%Y%m%d_%H%M%S)"
ssh $SERVER_USER@$SERVER "if [ -d $REMOTE_PATH ] && [ \"\$(ls -A $REMOTE_PATH)\" ]; then mkdir -p /root/backups && tar -czf /root/backups/$BACKUP_NAME.tar.gz -C $REMOTE_PATH . && echo '✅ 备份完成: /root/backups/$BACKUP_NAME.tar.gz'; else echo '⚠️  无需备份（目录为空）'; fi"
echo ""

# 上传文件
echo "4. 上传文件到服务器..."
rsync -avz --delete \
    --exclude='.DS_Store' \
    --exclude='*.map' \
    $LOCAL_BUILD_PATH/ \
    $SERVER_USER@$SERVER:$REMOTE_PATH/

echo ""
echo "======================================"
echo "✅ 部署完成！"
echo "======================================"
echo ""
echo "🌐 访问地址: http://$SERVER/tzai/"
echo ""
echo "📝 提示："
echo "1. 确保 Nginx 已配置 /tzai 路径"
echo "2. 确保后端服务已启动: http://103.47.80.172:8666"
echo "3. 如需配置 Nginx，请参考 tzai-backend/ruoyi-ui/build-prod.sh 中的示例"
echo ""
echo "🔍 验证部署："
echo "curl -I http://$SERVER/tzai/"
echo ""

